import { Component, Injector, Inject, Optional, OpaqueToken, OnInit, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/app-component-base';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import {
  API_BASE_URL,
  ListResultDtoOfClassGroupOutDto,
  ClassServiceProxy,
  ListResultDtoOfMicroClassListDto
} from '@shared/service-proxies/service-proxies';
import { AppConsts } from '@shared/AppConsts';
import { ClassGroupAddComponent } from '../class-group-add/class-group-add.component';
import { MicroClassAddComponent } from '../micro-class-add/micro-class-add.component';

@Component({
  moduleId: module.id,
  selector: 'class-group-list',
  templateUrl: 'class-group-list.component.html',
  styleUrls: ['class-group-list.component.scss'],
  animations: [appModuleAnimation()],
})
export class ClassGroupListComponent extends AppComponentBase implements OnInit {
  @ViewChild('createClassGroupModal')
  createClassGroupModal: ClassGroupAddComponent;

  @ViewChild('createMicroClassModal')
  createMicroClassModal: MicroClassAddComponent;
  classGroups: ListResultDtoOfClassGroupOutDto = null;
  classes: ListResultDtoOfMicroClassListDto = null;
  expendGroupId: number = null;
  downloadUrl: string = AppConsts.remoteServiceBaseUrl + '/file/download/';
  constructor(
    injector: Injector,
    private _classService: ClassServiceProxy,
  ) {
    super(injector);
  }
  ngOnInit(): void {
    this.getClassGroups();
  }
  getClassGroups(): void {
    this._classService.getClassGroupsAsync().subscribe((result: ListResultDtoOfClassGroupOutDto) => {
      this.classGroups = result;
    });
  }
  createClassGroup(id: number): void {
    this.createClassGroupModal.show(id);
  }
  deleteGroup(id: number): void {
    this._classService.deleteClassGroupAsync(id).subscribe(() => {
      this.getClassGroups();
    });
  }
  addClass(id: number): void {
    this.createMicroClassModal.show(id);
  }
  expandClassGroup(groupId: number): void {
    if (this.expendGroupId === groupId) {
      this.classes = null;
      this.expendGroupId = null;
    } else {
      this.expendGroupId = groupId;
      this._classService.getClassesAsync(groupId).subscribe((result: ListResultDtoOfMicroClassListDto) => {
        this.classes = result;
      });
    }
  }

  getClasses(): void {
    if (this.expendGroupId) {
      this._classService.getClassesAsync(this.expendGroupId).subscribe((result: ListResultDtoOfMicroClassListDto) => {
        this.classes = result;
      });
    }
  }

  modifyClass(groupId: number, classId: number): void {
    this.createMicroClassModal.show(groupId, classId);
  }
  deleteClass(classId: number): void {
    this._classService.deleteClassAsync(classId).subscribe(() => {
      this.getClasses();
    });
  }
}
